import os

from fontTools.ttLib import TTFont
from fontTools.ttLib.woff2 import decompress
from PIL import ImageFont, Image, ImageDraw
from io import BytesIO
import ddddocr


"""
# 目标站点下载的字体文件
woff_path = "./03337c30.woff"
# ttf 格式文件
ttf_path = './font.ttf'
# 将 woff文件转成 ttf 文件
decompress(woff_path, ttf_path)

font = TTFont(ttf_path)
"""

class FontConvert:
    def __init__(self,woff_name) -> None:
        #woff_name = 323432.woff
        dir = os.path.dirname(__file__)
        self.woff_name = woff_name
        self.woff_path= os.path.abspath( os.path.join( dir,woff_name))
        self.ttf_name = woff_name.split('.')[0]+'.ttf'
        self.ttf_path = os.path.abspath( os.path.join(dir,self.ttf_name))
    
    def get_dict(self):
        decompress(self.woff_path, self.ttf_path)
        
        woff_dict={}
        
        font = TTFont(self.ttf_path)
        # 图片宽度和高度
        img_size = 512
        font_img = ImageFont.truetype(self.ttf_path, img_size)
        ocr = ddddocr.DdddOcr(show_ad=False)
        for cmap_code, glyph_name in font.getBestCmap().items():
            # print(cmap_code,glyph_name)

            # 实例化一个图片对象
            img = Image.new('1', (img_size, img_size), 255)

            # 绘制图片
            draw = ImageDraw.Draw(img)
            # 将编码读取成字节
            txt = chr(cmap_code)

            x, y = draw.textsize(txt, font=font_img)

            draw.text(((img_size - x) // 2, (img_size - y) // 2), txt, font=font_img, fill=0)
            bytes_io = BytesIO()
            img.save(bytes_io, format="PNG")
            word = ocr.classification(bytes_io.getvalue())  # 识别字体
            woff_dict[glyph_name] = word
        return woff_dict
    def __del__(self):
        os.remove(self.woff_path)
        os.remove(self.ttf_path)

if __name__ == '__main__':
    font = FontConver("432017e7.woff")
    print(font.get_dict())

